package com.youngball.service.impl;

import CommandEntity.HardWare;
import com.syg.manager.service.scheduler.LightCtrlService;
import com.youngball.netty.LightServerInitHandler;
import com.youngball.utill.ObjectNullUtils;
import com.youngball.web.config.MyDefineException;
import io.netty.channel.Channel;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.youngball.netty.LightServerInitHandler.channelMap;

/**
 * Created by liaopingzhu on 2016/12/22.
 */
@Component
public class LightCtrlServiceImpl implements LightCtrlService {

    @Override
    public HardWare.LightRequest handleLight(com.syg.manager.entity.LightCommand lightCommand) {
        HardWare.LightRequest response = null;
        //找到web客户端所对应的树莓派channel
        Channel channel = (Channel) channelMap.get(lightCommand.getCid().split("club")[1]);
        try {
            if(channel == null){
                throw new MyDefineException("没有找到对应的树莓派灯控客户端");
            }
            if(lightCommand.getCmd() == 2){
                //cmd = 2 查询  json --> protobuf
                HardWare.LightRequest request = HardWare.LightRequest
                        .newBuilder()
                        .setCid(lightCommand.getCid())
                        .setCmd(HardWare.LightRequest.Cmd.QUERY)
                        .setTyeValue(lightCommand.getType())
                        .setVersion(lightCommand.getVersion()).build();
                LightServerInitHandler.localstate = null;
                channel.writeAndFlush(request);
            }else {
                //开关灯
                //实例化protobuf的两种方式
                HardWare.LightRequest.Builder builder = HardWare.LightRequest.newBuilder();
                builder.setCid(lightCommand.getCid());
                //CLOSE = 0;    //关灯 OPEN = 1;	//开灯
                builder.setCmdValue(lightCommand.getCmd());
                builder.setTyeValue(lightCommand.getType());
                for(com.syg.manager.entity.CommandData data : lightCommand.getCommandDatas()){
                    builder.putData(data.getKey(),data.getValue());
                }
                HardWare.LightRequest request = builder.build();

                LightServerInitHandler.localstate = null;
                channel.writeAndFlush(request);
            }
            if("http".equals(lightCommand.getClienType())){
                //等待返回结果
                String result = getOrder();
                if("timeout".equals(result)){
                    throw new MyDefineException("连接超时");
                }
                response = LightServerInitHandler.localstate;
            }
        } catch (InterruptedException e){
            e.printStackTrace();
        } catch (MyDefineException e){
            throw e;
        } catch (Exception e){
            e.printStackTrace();
            throw new MyDefineException("inner error"+e.getMessage());
        }
        return response;
    }

    @Override
    public String TestDubbo() {
        String str = "test";
        System.out.println(str);
        return str;
    }

    @Override
    public List<Map> String2Maps(String str) {
        List<Map> maps = new ArrayList<Map>();
        str = str.substring(1,str.length()-1);
        for(String a : str.split(",")){
            Map map = new HashMap();
            map.put(a.split(":")[0],a.split(":")[1]);
            maps.add(map);
        }
        return maps;
    }

    public String getOrder() throws InterruptedException {
        String name="";
        long startTime= System.currentTimeMillis();
        while ("".equals(name)){
            Thread.sleep(50);
            long endTime= System.currentTimeMillis();
            if(ObjectNullUtils.isNotBlank(LightServerInitHandler.localstate)){
                name=LightServerInitHandler.localstate.getResultMessage() ;
            }
            if (endTime-startTime>5000){
                System.out.println("超时,获取失败");
                name = "timeout";
                return name ;
            }
        }
        return name;
    }


}
